package com.linghang.wusthelper.spider.library;

import com.linghang.wusthelper.entity.primary.BookRent;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * @author origin
 * 图书当前借阅爬虫
 */
public class LibBookRentSpider implements PageProcessor {

    private List<BookRent> bookRentList;

    private String lock;

    private Site site = Site.me().setRetryTimes(3).setTimeOut(3000)
            .setDomain("www.lib.wust.edu.cn")
            .addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
            .addHeader("Accept-Encoding","gzip,deflate,sdch")
            .addHeader("Accept-Language", "zh-CN,zh;q=0.8")
            .addHeader("Connection", "keep-alive")
            .addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");


    public LibBookRentSpider(String PHPSESSID, List<BookRent> bookRentList,String lock){
        site.addCookie("PHPSESSID",PHPSESSID);
        this.bookRentList = bookRentList;
        this.lock = lock;
    }

    @Override
    public void process(Page page) {
        String snums = page.getHtml().xpath("//*[@id=\"mylib_content\"]/p[2]/b[1]/text()").get();
        if (!snums.equals("")){
            //  获取数量
            int nums = Integer.valueOf(snums);
            for (int i = 2;i < nums+2;i++){
                String path = "//*[@id=\"mylib_content\"]/table/tbody/tr["+i+"]";
                String bookCode = page.getHtml().xpath(path+"/td[1]/text()").get();
                String bookName = page.getHtml().xpath(path+"/td[2]/a/text()").get();
                String bookUrl = page.getHtml().xpath(path+"/td[2]/a/@href").get();
                String rentTime = page.getHtml().xpath(path+"/td[3]/text()").get();
                String returnTime = page.getHtml().xpath(path+"/td[4]/font/text()").get();
                String renenNums = page.getHtml().xpath(path+"/td[5]/text()").get();
                String bookPlace = page.getHtml().xpath(path+"/td[6]/text()").get();

                BookRent bookRent = new BookRent();
                bookRent.setBookCode(bookCode);
                bookRent.setBookName(bookName);
                bookRent.setBookUrl(bookUrl);
                bookRent.setRentTime(rentTime);
                bookRent.setReturnTime(returnTime);
                bookRent.setRenewNum(renenNums);
                bookRent.setBookPlace(bookPlace);

                bookRentList.add(bookRent);
            }
        }
        synchronized (lock){
            lock.notify();
        }
    }

    @Override
    public Site getSite() {
        return site;
    }
}